<template>
  <t-card style="height: 87vh">
    <t-form ref="form" :colon="true" resetType="initial" :data="formData" labelWidth="160px" :rules="rules">
      <t-row style="row-gap:24px">
        <t-col :span="6">
          <t-form-item label="姓名" name="name">
            <t-input clearable style="width:390px" v-model="formData.name" placeholder="请输入"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="性别" name="sex">
            <t-select clearable style="width:390px" :options="dict.type.sys_user_sex" v-model="formData.sex"></t-select>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="身份证号" name="idCard">
            <t-input style="width: 390px" @change="onIdCardChange" placeholder="请输入身份证号" clearable
              v-model="formData.idCard"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="出生年月" name="birthDate">
            <t-date-picker disabled :disable-date="{
      after: dayjs().endOf('month').add(-18, 'year').format()
    }" clearable allow-input style="width: 390px" mode="month" v-model="formData.birthDate"></t-date-picker>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="民族" name="national">
            <t-select clearable style="width:390px" :options="dict.type.national"
              v-model="formData.national"></t-select>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="政治面貌" name="politicsStatus">
            <t-select clearable style="width:390px" :options="dict.type.politics_status"
              v-model="formData.politicsStatus"></t-select>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="电子信箱" name="email">
            <t-input style="width: 390px" clearable v-model="formData.email"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="联系电话" name="phone">
            <t-input style="width: 390px" placeholder="请输入手机号码" clearable v-model="formData.phone"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="学历" name="education">
            <t-select style="width: 390px" v-model="formData.education" clearable placeholder="请选择学历"
              :options="dict.type.education">
            </t-select>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="学位" name="degree">
            <t-select style="width: 390px" v-model="formData.degree" clearable placeholder="请选择学位"
              :options="dict.type.degree">
            </t-select>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="职务" name="duty">
            <t-input clearable style="width:390px" v-model="formData.duty"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="毕业院校" name="school">
            <t-input style="width: 390px" clearable v-model="formData.school"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="技术职称" name="profTitId">
            <t-tree-select style="width:390px" @change="onProfTitIdChange" clearable filterable
              :treeProps="{ keys: { value: 'id', label: 'name' }, valueMode: 'onlyLeaf' }" v-model="formData.profTitId"
              :data="profTitOptions" placeholder="技术职称"></t-tree-select>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="职称" name="profTit">
            <t-select disabled style="width:390px" v-model="formData.profTit" clearable placeholder="请选择职称"
              :options="dict.type.prof_tit"></t-select>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="所学专业" name="majorName">
            <t-input v-model="formData.majorName" clearable placeholder="请输入专业" style="width: 390px" />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="现从事专业" name="majorNowName">
            <t-input v-model="formData.majorNowName" clearable placeholder="请输入专业" style="width: 390px" />
          </t-form-item>
        </t-col>
        <!--          <t-col :span="6">-->
        <!--            <t-form-item label="是否内部单位" name="isInnerCompany">-->
        <!--              <t-switch-->
        <!--                size="large"-->
        <!--                v-model="formData.isInnerCompany"-->
        <!--                :label="['是', '否']"-->
        <!--                :customValue="['1', '0']"-->
        <!--                @change="()=>{formData.company='';formData.companyId=null}"-->
        <!--              ></t-switch>-->
        <!--            </t-form-item>-->
        <!--          </t-col>-->
        <t-col :span="6">
          <t-form-item label="所在单位" help="搜索不到请切换内外部单位" name="company">
            <t-tree-select @change="deptChange" v-if="formData.isInnerCompany === '1'" style="width:390px" clearable
              filterable :treeProps="{ keys: { value: 'label' } }" v-model="formData.company" :data="deptMenuOptions"
              placeholder="选择单位">
              <template #label>
                <t-switch size="medium" v-model="formData.isInnerCompany" :label="['内部', '外部']"
                  :customValue="['1', '0']"
                  @change="() => { formData.company = ''; formData.companyId = null }"></t-switch>
              </template>
            </t-tree-select>
            <t-select v-else v-model="formData.company" creatable filterable placeholder="请输入" :loading="applyLoading"
              @search="remoteCompanyMethod" :options="companyOptions" @create="createCompanyOptions"
              style="width: 390px">
              <template #label>
                <t-switch size="medium" v-model="formData.isInnerCompany" :label="['内部', '外部']"
                  :customValue="['1', '0']"
                  @change="() => { formData.company = ''; formData.companyId = null }"></t-switch>
              </template>
            </t-select>
            <!--              <t-input v-else clearable style="width:390px" v-model="formData.company"></t-input>-->
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="通讯地址" name="address">
            <t-input style="width: 390px" clearable v-model="formData.address"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="邮编" name="postCode">
            <t-input style="width: 390px" clearable v-model="formData.postCode"></t-input>
          </t-form-item>
        </t-col>


      </t-row>
    </t-form>

    <template #footer>
      <t-row style="margin-top: 20px;text-align: center">
        <t-col :span="12">
          <t-space :size="10">
            <t-button theme="primary" :loading="applyLoading" @click="onSubmit(1)">{{
      applyLoading ? '提交中...' : '暂存'
    }}
            </t-button>
            <t-button theme="primary" :loading="applyLoading" @click="onSubmit(2)">{{
      applyLoading ? '提交中...' : '提交'
              }}
            </t-button>
          </t-space>
        </t-col>
      </t-row>
    </template>
  </t-card>
</template>

<script>
import { getIdCardBirthday, getIdCardAge } from '@/utils/common';
import dayjs from "dayjs"

export default {
  name: "add-edit-member",
  dicts: ["sys_user_sex", "education", "prof_tit", "degree", "national", "politics_status"],
  props: ["header"],
  data () {
    return {
      companyOptions: [],
      applyLoading: false,
      applyLoading: false,
      visible: true,
      loading: false,
      dayjs,
      profTitOptions: [],
      deptMenuOptions: [],
      objId:null,
      formData: {
        companyId: null,
        politicsStatus: '',
        national: '',
        degree: '',
        school: '',
        postCode: '',
        email: '',
        address: '',
        phone: '',
        name: '',
        sex: '',
        birthDate: '',
        duty: '',
        profTit: '',
        profTitId: null,
        majorName: '',
        majorNowName: '',
        company: '',
        task: '',
        education: '',
        idCard: '',
        isAssist: '0',
        isInnerCompany: '1',
      },
      rules: {
        national: [
          {
            required: true,
            message: "民族不能为空",
          }
        ],
        politicsStatus: [
          {
            required: true,
            message: "政治面貌不能为空",
          }
        ],
        name: [
          {
            required: true,
            message: "姓名不能为空",
          }
        ],
        school: [
          {
            required: true,
            message: "毕业院校不能为空",
          }
        ],
        sex: [
          {
            required: true,
            message: "性别不能为空",
          }
        ],
        birthDate: [
          {
            required: true,
            message: "出生年月不能为空",
          }
        ],
        duty: [
          {
            required: true,
            message: "职务不能为空",
          }
        ],
        profTit: [
          {
            required: true,
            message: "职称不能为空",
          }
        ],
        profTitId: [
          {
            required: true,
            message: "技术职称不能为空",
          }
        ],
        education: [{
          required: true,
          message: "学历不能为空",
        }],
        majorName: [
          {
            required: true,
            message: "所学专业不能为空",
          }
        ],
        majorNowName: [
          {
            required: true,
            message: "现从事专业不能为空",
          }
        ],
        company: [
          {
            required: true,
            message: "所在单位不能为空",
          }
        ],
        task: [
          {
            required: true,
            message: "不能为空",
          }
        ],
        isInnerCompany: [
          {
            required: true,
            message: "不能为空",
          }
        ],
        idCard: [
          {
            required: true,
            message: "身份证号不能为空",
          },
          {
            message: "身份证号不正确",
            pattern: /^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/,
          },
        ],
        email: [
          {
            required: true,
            message: "邮箱不能为空",
          },
          { email: { ignore_max_length: true }, message: '请输入正确的邮箱地址' }
        ],
        degree: [
          {
            required: true,
            message: "学位不能为空",
          },
        ],
        phone: [
          {
            required: true,
            message: "联系电话不能为空",
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "联系电话请输入正确的手机号码",
          },
        ],
      },
    }
  },
  watch: {
    // objId: {
    //   immediate: true,
    //   handler (val) {
    //     if (val) {
    //       this.getObj();
    //     }
    //   }
    // }
  },
  created () {
    this.objId = this.$route.query.id; // 从路由参数中获取id
console.log(this.objId);

    if (!this.objId) {
      Promise.all([this.getDeptTreeSelect(this.$store.state.user.deptId), this.getProfTitTreeSelect()]);
    } else {
      this.getObj();
    }
    // this.$refs.form.setValidateMessage( {
    //   type: 'default',
    //   message: '搜索不到请切换外部单位后手输',
    // });

  },
  methods: {
    async getObj () {
      console.log('---------------');

      await Promise.all([this.getDeptTreeSelect(this.$store.state.user.deptId), this.getProfTitTreeSelect()]);
      this.$api.kjrc.talents.getRCInfo(this.objId).then((response) => {
        this.formData = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    createCompanyOptions (value) {
      this.companyOptions.push({
        label: `${value}`,
        value,
      });
    },
    remoteCompanyMethod (search) {
      this.applyLoading = true;
      this.$api.system.dept.selectAllOutDeptList({ deptName: search }).then(response => {
        this.companyOptions = response.data.map(val => ({
          ...val,
          label: `${val.deptName}`,
          value: val.deptName,
        }));
        this.applyLoading = false;
      }).catch((e) => {
        this.applyLoading = false;
        this.$message.error(e.toString());
      });
    },
    onSubmit (type) {
      if (type === 1) {
        this.applyLoading = true;
        if (!this.formData.id) {
          this.$api.kjrc.talents.add(this.formData).then(response => {
            this.formData.id = response.data.id;
            this.applyLoading = false;
            this.$message.success('暂存成功');
          }).catch((e) => {
            this.applyLoading = false;
            this.$message.error(e.toString());
          });
        } else {
          this.$api.kjrc.talents.update(this.formData).then(response => {
            this.applyLoading = false;
            this.$message.success('暂存成功');
          }).catch((e) => {
            this.applyLoading = false;
            this.$message.error(e.toString());
          });
        }
      } else {
        this.$refs.form.validate().then((validateResult) => {
          if (validateResult === true) {
            // const isValidate = this.$refs["opinion-fixed-list"].checkData()
            // if (!isValidate) {
            //   return false
            // }
            const confirmDia = this.$dialog.confirm({
              header: "提交后不可再编辑会进入审批流程",
              body: `是否确认提交？`,
              theme: "warning",
              onConfirm: ({ e }) => {
                confirmDia.update({
                  confirmBtn: {
                    loading: true,
                  },
                })
                this.applyLoading = true;
                this.$api.kjrc.talents.submit(this.formData).then(response => {
                  this.applyLoading = false;
                  confirmDia.destroy();
                  this.$message.success('提交成功');
                  // this.close();
                }).catch((e) => {
                  this.applyLoading = false;
                  confirmDia.update({
                    confirmBtn: {
                      loading: false,
                    },
                  })
                  this.$message.error(e.toString());
                });
              },
            })
          } else {
            const firstError = Object.values(validateResult)[0]?.[0]?.message;
            this.$message.error(firstError);
          }
        });
      }
    },
    closeDialog () {
      this.$emit("update:visible", false);
    },
    onIdCardChange (val) {
      const birthday = getIdCardBirthday(val);
      if (birthday !== "") {
        this.formData.birthDate = birthday.slice(0, 7)
        this.$api.kjxm.project.findProjectMember(val).then(response => {
          this.oldMember = response.data;
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      }
    },
    deptChange (val, content) {
      this.formData.companyId = content.data.id;
    },
    getDeptTreeSelect (id) {
      return this.$api.system.dept.treeSelectAllIn().then(response => {
        this.deptMenuOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getProfTitTreeSelect () {
      return this.$api.system.profTit.list().then(response => {
        this.profTitOptions = this.handleTree(response.data, "id");
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    onProfTitIdChange (val, content) {
      this.formData.profTit = content.node.data.level;
    },
  }
}
</script>

<style scoped></style>
